﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.IO.IsolatedStorage;
using System.Xml.Linq;
using System.IO;
using System.Linq;

namespace AllTalk
{
    public class ChatViewModel : ViewModelBase
    {
        private static XName ChatLog = "ChatLog";

        internal Friend Friend { get; private set; }

        private string _filename;
        
        public ImageSource Image
        {
            get { return this.Friend.Picture.Source; }
        }

        public string Title
        {
            get { return this.Friend.Name; }
        }

        public string Subtitle
        {
            get { return this.Friend.Email; }
        }

        public Presence Presence
        {
            get { return this.Friend.Presence; }
        }

        private string _status;
        
        public string Status
        {
            get { return _status; }
            set
            {
                if (_status != value)
                {
                    _status = value;
                    NotifyPropertyChanged("Status");
                }
            }
        }

        ObservableCollection<ChatMessageViewModel> _chatMessageViewModels;
        
        public ObservableCollection<ChatMessageViewModel> ChatMessageViewModels
        {
            get
            {
                if (_chatMessageViewModels == null)
                {
                    _chatMessageViewModels = new ObservableCollection<ChatMessageViewModel>();
                }
                return _chatMessageViewModels;
            }
        }

        internal ChatViewModel(Friend friend)
        {
            this.Friend = friend;
            _filename = String.Concat("ChatLog - ", this.Friend.Email, ".xml"); ;
            this.Load();
        }

        internal void Load()
        {
            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (store.FileExists(_filename))
                {
                    using (var stream = store.OpenFile(_filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    {

                        XElement rootElement = XElement.Load(stream);
                        if (rootElement.Name == ChatLog)
                        {
                            foreach (var message in rootElement.Elements("message"))
                            {
                                this.ChatMessageViewModels.Add(new ChatMessageViewModel(new ChatMessage(message)));
                            }
                        }
                    }
                }
            }
        }

        internal void Save()
        {
            if(this._chatMessageViewModels == null || this._chatMessageViewModels.Count == 0)
            {
                // there are no messages to save.
                return;
            }

            using (var store = IsolatedStorageFile.GetUserStoreForApplication())
            {
                using (var stream = store.OpenFile(_filename, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    XElement rootElement = new XElement(ChatLog);
                    int count = 0;
                    // Save the last 'x' messages.
                    for (int i = this.ChatMessageViewModels.Count - 1; i >= 0 && count <= StorageConstants.CoutOfMessages; i--)
                    {
                        this.ChatMessageViewModels[i].ChatMessage.Save(rootElement);
                        count++;
                    }
                    rootElement.Save(stream);
                }
            }
        }
    }

    public class ChatMessageViewModel : ViewModelBase
    {
        internal ChatMessage ChatMessage { get; private set;}

        internal ChatMessageViewModel(ChatMessage message)
        {
            this.ChatMessage = message;
        }
        
        public string Message
        {
            get
            { 
                return this.ChatMessage.Message;
            }
        }

        public string Timestamp
        {
            get 
            {
                return this.ChatMessage.Timestamp.ToString("f");
            }
            
        }

        public TextAlignment Alignment
        {
            get
            {
                return this.ChatMessage.Sender == App.DataModel.CurrentJid ? TextAlignment.Left : TextAlignment.Right;
            }
        }

        private static Thickness LeftAlign = new Thickness(20, 20, 0, 0);
        private static Thickness RightAlign = new Thickness(70, 20, 0, 0);

        public Thickness Margin
        {
            get
            {
                return this.ChatMessage.Sender == App.DataModel.CurrentJid ? LeftAlign : RightAlign;
            }
        }
    }
}

